package org.example.route.service.impl;

import org.example.route.mapper.CityMapper;
import org.example.route.mapper.StationMapper;
import org.example.route.mapper.StationRouteMapper;
import org.example.route.model.dto.BaseRequest;
import org.example.route.model.dto.StationDTO;
import org.example.route.model.dto.StationQueryDTO;
import org.example.route.model.pojo.Station;
import org.example.route.model.pojo.StationRoute;
import org.example.route.model.vo.StationShowVO;
import org.example.route.service.StationService;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class StationServiceImpl implements StationService {

    @Autowired
    private StationMapper stationMapper;
    @Autowired
   private CityMapper cityMapper;
    @Autowired
    private StationRouteMapper stationRouteMapper;

    /**
     *
     * 工具链
     *
     * **/
    @Tool(name = "listStation", description = "查询并获取车站站点的信息，包括车站名称，所在城市名称等，如果参数为空就查全部的" +
            "，如果传来的是城市或者省份的名称，你可以通过工具链调用listProvince,listCity等方法最终得到cityId来查询")
    public List< StationShowVO> list(@ToolParam(description = "站点名称的模糊查询，比如'北'，'北京' ") String name,
                                     @ToolParam(description = "车站所在的城市id，如果为空就查全部的") Long cityId) {

        StationQueryDTO stationQueryDTO = new StationQueryDTO(name,cityId);
        return list(stationQueryDTO);


    }


    @Override
    public void add(StationDTO stationDTO) {
        stationMapper.add(stationDTO);
    }

    @Override
    public List<StationShowVO> list(StationQueryDTO stationQueryDTO) {
        List<StationShowVO> stationShowVOList = new ArrayList<>();
        List<Station> stationList = stationMapper.list(stationQueryDTO);
        for (Station station : stationList) {
            StationShowVO stationShowVO = new StationShowVO(station.getId(), station.getName(), cityMapper.getCityNameById(station.getCityId()),station.getCityId());
            stationShowVOList.add(stationShowVO);
        }

        return stationShowVOList;

    }






    @Override
    public void delete(BaseRequest baseRequest)
    {
         Station station = stationMapper.getById(Long.parseLong(baseRequest.getKey()));
         if (Objects.isNull(station))
         {
             throw new RuntimeException("站点不存在");
         }

         List<StationRoute> stationRouteList = stationRouteMapper.listByStationId(station.getId());
         if (!stationRouteList.isEmpty())
         {
             throw new RuntimeException("该站点有线路，请先删除线路");
         }

         stationMapper.deleteById(station.getId());


    }
}
